<?php
//APP端微信支付回调接口
//20150805 by ajsong
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('ROOT_PATH', dirname(__FILE__));
define('FRAMEWORK_PATH', ROOT_PATH . '/framework');
define('PROTECTED_PATH', ROOT_PATH . '/protected');
define('APP_PATH', PROTECTED_PATH . '/api');
define('MODEL_PATH', PROTECTED_PATH . '/model');
define('TEMPLATE_PATH', PROTECTED_PATH . '/template/wap' );
require_once(FRAMEWORK_PATH . '/class/request/request.php');
require_once(FRAMEWORK_PATH . '/global.php');
require_once(PROTECTED_PATH . '/config.php');
require_once(FRAMEWORK_PATH . '/wenyan.php');
require_once(APP_PATH . '/core.php');
require_once(MODEL_PATH . '/base.model.php');
require_once(FRAMEWORK_PATH . '/class/smarty-3.1.18/libs/Smarty.class.php');


if (!get_magic_quotes_gpc()) {
    $_GET   = addslashes_deep($_GET);
    $_POST  = addslashes_deep($_POST);
    $_COOKIE = addslashes_deep($_COOKIE);
    $_SERVER = addslashes_deep($_SERVER);
}
$request = new Request();

$smarty = new Smarty();
$smarty->setTemplateDir(TEMPLATE_PATH);
$smarty->setCompileDir(ROOT_PATH . '/temp/templates_c/wap/');
$smarty->setCacheDir(ROOT_PATH . '/temp/cache/wap/');

// $cart = c('cart');
// $_GET = array('order_sn'=>$_GET['order_sn']);
// $cart->order_complete(false,"18121023012613992");
// exit;

libxml_disable_entity_loader(true); //修复XXE漏洞
//$xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; //PHP7以上不支持
$xml = file_get_contents('php://input');
write_log($xml);
if (!empty($xml)) {
	$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
	$return_str = '';

	//writeLog(json_encode($obj)."\n", "wxpay.txt");
	if ($obj->result_code == 'SUCCESS') {
		//支付成功
		//$openid = $obj->openid; //用户的微信标识
		$transaction_id = isset($obj->transaction_id) ? $obj->transaction_id : ""; //微信支付订单号
		$trade_no = $transaction_id;
		$out_trade_no = $obj->out_trade_no; //商户订单号
		$total_fee = $obj->total_fee; //支付金额,单位分
		$time_end = $obj->time_end; //支付时间,格式为yyyyMMddHHmmss

		//购买订单
		//$sql = "UPDATE mmx_order SET status=1 WHERE id='{$out_trade_no}'";
		//先判断是否为单个订单（从会员中心我的订单处支付），如果是，则处理该订单，否则，为分单后的总订单
		$flag = substr($out_trade_no, 0, 2);
		//echo $flag;exit;
		if ($flag == 'CZ') { //充值
			$sql = "SELECT * FROM {$tbp}member_recharge WHERE order_sn='{$out_trade_no}'";
			write_log($sql);
			$row = $db->get_row($sql);
			if ($row && $row->status==0) {
				$sql = "UPDATE {$tbp}member_recharge SET status='1', pay_time='".time()."', trade_no='{$trade_no}' WHERE order_sn='{$out_trade_no}'";
				write_log($sql);
				$db->query($sql);
				$sql = "UPDATE {$tbp}member SET `money`=`money`+{$row->recharged_money} WHERE id='{$row->member_id}'";
				write_log($sql);
				$db->query($sql);
				$sql = "INSERT INTO {$tbp}member_money_history(member_id, `money`, memo, type, parent_id, add_time, status)
					VALUES('{$row->member_id}', '{$row->recharged_money}', '余额充值', '2', '{$row->id}', '".time()."', '1')";
				write_log($sql);
				$db->query($sql);
			}
		} else if ($flag == 'DJ') { //等级
			$sql = "UPDATE {$tbp}member_grade_order SET status='1', pay_time='".time()."', trade_no='{$trade_no}' WHERE order_sn='{$out_trade_no}'";
			write_log($sql);
			$db->query($sql);
			$sql = "SELECT member_id, grade_id FROM {$tbp}member_grade_order WHERE order_sn='{$out_trade_no}'";
			write_log($sql);
			$row = $db->get_row($sql);
			if ($row) {
				$sql = "SELECT score FROM {$tbp}member_grade WHERE id='{$row->grade_id}'";
				write_log($sql);
				$score = intval($db->get_var($sql));
				$sql = "UPDATE {$tbp}member SET grade_id='{$row->grade_id}', grade_score='{$score}' WHERE id='{$row->member_id}'";
				write_log($sql);
				$db->query($sql);
				$member_mod = m('member');
				$member_mod->update_grade_from_score($row->member_id);
			}
		} else if ($flag == 'CJ') { //差价
			$sql = "SELECT * FROM {$tbp}order WHERE differ_order_sn='{$out_trade_no}'";
			write_log($sql);
			$rs = $db->get_results($sql);
			if ($rs) {
				foreach ($rs as $k=>$o) {
					$sql = "UPDATE {$tbp}order SET differ_money='0', differ_pay_time='".time()."', differ_trade_no='{$trade_no}' WHERE id='{$o->id}'";
					write_log($sql);
					$db->query($sql);
				}
			}
		} else { //订单
			$sql = "SELECT * FROM {$tbp}order WHERE (pay_order_sn='{$out_trade_no}' OR parent_order_sn='{$out_trade_no}') AND status=0";
			write_log($sql);
			$rs = $db->get_results($sql);
			if ($rs) {
				$member_id = 0;
				$integral = 0;
				foreach ($rs as $k=>$o) {
					$sql = "UPDATE {$tbp}order SET status='1', pay_time='".time()."', trade_no='{$trade_no}' WHERE id='{$o->id}'";
					write_log($sql);
					$db->query($sql);
					//增加积分
					$sql = "SELECT g.give_integral, og.quantity FROM {$tbp}goods g LEFT JOIN {$tbp}order_goods og ON og.goods_id=g.id
						WHERE og.order_id='{$o->id}'";
					write_log($sql);
					$goods = $db->get_results($sql);
					if ($goods) {
						foreach ($goods as $kg=>$g) {
							$integral += $g->give_integral * $g->quantity;
						}
					}
					$member_id = $o->member_id;
				}
				$sql = "UPDATE {$tbp}member SET `integral`=`integral`+{$integral} WHERE id='{$member_id}'";
				write_log($sql);
				$db->query($sql);
				//调用订单支付成功接口,更新库存、销量等
				$cart = c('cart');
				$_GET = array('order_sn'=>$out_trade_no);
				write_log("call order_complete: {$out_trade_no}");
				$cart->order_complete(false, $out_trade_no);
			}
		}
		write_log("\n==============================");

		$return_str = "<xml>
				<return_code><![CDATA[SUCCESS]]></return_code>
				<return_msg><![CDATA[OK]]></return_msg>
			</xml>";
	} else {
		//结果为支付失败
		write_log("\nwxpay fail\n==============================");
		$return_str = "<xml>
				<return_code><![CDATA[FAIL]]></return_code>
				<return_msg><![CDATA[OK]]></return_msg>
			</xml>";
	}

	echo $return_str;
}

/*
<xml>
  <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
  <attach><![CDATA[支付测试]]></attach>
  <bank_type><![CDATA[CFT]]></bank_type>
  <fee_type><![CDATA[CNY]]></fee_type>
  <is_subscribe><![CDATA[Y]]></is_subscribe>
  <mch_id><![CDATA[10000100]]></mch_id>
  <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
  <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
  <out_trade_no><![CDATA[1409811653]]></out_trade_no>
  <result_code><![CDATA[SUCCESS]]></result_code>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
  <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
  <time_end><![CDATA[20140903131540]]></time_end>
  <total_fee>1</total_fee>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
</xml>
*/
?>